import express from "express";
import mysql from "mysql2/promise";
import fs from "fs";
import jsYaml from "js-yaml";
import Result from "../utils/Result.js";
import path from "path";
import crypto from "node:crypto"

const router = express.Router();
// 读取配置文件
const configPath = path.resolve(process.cwd(), "./db.config.yaml");
const yaml = fs.readFileSync(configPath, "utf8");
// 加载配置文件
const config = jsYaml.load(yaml);
// 创建数据库连接
const sql = await mysql.createConnection({
  ...config.db,
});

// 添加用户
router.post("/addUser", async (req, res) => {
  let { user_name, password, email, phone } = req.body;
  // 查询用户名是否已存在
  const [rows] = await sql.query("SELECT * FROM user WHERE user_name = ?", [user_name]);
  if (rows.length > 0) {
    res.json(Result.error("用户名已存在"));
    return;
  }
  // 如果用户不存在，则添加用户，并且返回新增的用户ID
  // 对密码进行md5加密
  password = crypto.createHash('md5').update(password).digest('hex')
  // 获取当前时间
  let create_time = new Date()
  // 执行插入方法
  const [data] = await sql.query(
    "INSERT INTO user (user_name, password, email, phone,create_time) VALUES (?, ?, ?, ?, ?)",
    [user_name, password, email, phone, create_time]
  );
  res.json(Result.success(data.insertId));
});

// 删除用户
router.post("/deleteUser", async (req, res) => {
  let { id } = req.query;
  // 执行删除方法
  await sql.query("DELETE FROM user WHERE id = ?", [id]);
  res.json(Result.success());
})

// 查询指定id信息
router.get("/getUserById", async (req, res) => {
  let { id } = req.query;
  // 执行查询方法
  const [data] = await sql.query("SELECT id,user_name,phone,email,create_time FROM user WHERE id = ?", [id]);
  res.json(Result.success(data[0]));
})

// 根据id修改用户
router.post("/updateUser", async (req, res) => {
  let { id, user_name, email, phone } = req.body;
  // 执行修改方法
  const [data] = await sql.query("update user set user_name = ?, email = ?, phone = ? where id = ?",
    [user_name, email, phone, id]
  )
  res.json(Result.success(data))
})

// 查询所有用户
router.get("/getAllUsers", async (req, res) => {
  let user_name = req.query.user_name;
  const [data] = await sql.query("SELECT * FROM user WHERE user_name LIKE ?", [`%${user_name}%`]);
  res.json(Result.success(data));
});

export default router;
